import axios, { AxiosInstance } from 'axios';
import { ElLoading } from 'element-plus';

import type { HYRequestConfig, HYRequestInterceptors } from './type';

const DEFAULT_LOADING = true;

class HYRequest {
  instance: AxiosInstance;
  isShowLoading: boolean;
  interceptors?: HYRequestInterceptors;
  loadingInstance?: any;

  constructor(config: HYRequestConfig) {
    // 创建实例
    this.instance = axios.create(config);
    // 保存基本信息
    this.isShowLoading = config.isShowLoading ?? DEFAULT_LOADING;
    this.interceptors = config.interceptors;
    this.handleInterceptors();
  }
  private handleInterceptors() {
    this.interceptorsRequest();
    this.interceptorsResponse();
  }
  private interceptorsRequest() {
    // 单个请求的拦截器，从config中取出的拦截器是对应的实例的拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );

    // 全局拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.isShowLoading) {
          this.loadingInstance = ElLoading.service({
            lock: true,
            text: '正在请求数据....',
            background: 'rgba(0, 0, 0, 0.5)'
          });
        }
        return config;
      },
      (err) => {
        return err;
      }
    );
  }
  private interceptorsResponse() {
    // 单个请求的响应拦截器
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );
    // 所有请求的响应拦截器
    this.instance.interceptors.response.use(
      (res) => {
        setTimeout(() => {
          this.loadingInstance?.close();
        }, 1 * 1000);
        const data = res.data;
        if (data?.returnCode === '-1001') {
          console.log('请求失败~, 错误信息');
        } else {
          return data;
        }
      },
      (err) => {
        // 将loading移除
        this.loadingInstance?.close();

        // 例子: 判断不同的HttpErrorCode显示不同的错误信息
        if (err.response.status === 404) {
          console.log('404的错误~');
        }
        return err;
      }
    );
  }
  request<T>(config: HYRequestConfig<T>): Promise<T> {
    return new Promise((resolve, reject) => {
      // 1.单个请求对请求config的处理
      if (config.interceptors?.requestInterceptor) {
        config = config.interceptors.requestInterceptor(config);
      }
      // 2.判断是否需要显示loading
      if (config.isShowLoading === false) {
        this.isShowLoading = config.isShowLoading;
      }

      this.instance
        .request<any, T>(config)
        .then((res) => {
          // 1.单个请求对数据的处理
          if (config.interceptors?.responseInterceptor) {
            res = config.interceptors.responseInterceptor(res);
          }

          // 2.将showLoading设置true, 这样不会影响下一个请求
          this.isShowLoading = true;
          resolve(res);
        })
        .catch((err) => {
          this.isShowLoading = DEFAULT_LOADING;
          reject(err);
          return err;
        });
    });
  }
  get<T>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'GET' });
  }

  post<T>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'POST' });
  }

  delete<T>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'DELETE' });
  }

  patch<T>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: 'PATCH' });
  }
}

export default HYRequest;
